/*
 * protocol.h
 *
 *  Created on: Jun 7, 2012
 *      Author: esl32
 */

#ifndef PROTOCOL_H_
#define PROTOCOL_H_

#include <stdio.h>
#include <string.h>
#include <fcntl.h>

#define START 0
#define FRAMEDLE 1
#define DATA 2
#define DATADLE 3

#define DLE 0x10
#define ETX 0x03

#define PARSING 0
#define READY 1
#define MALFORMED 2
#define CHECKSUM_INCORRECT 3

#define RESET 0x40
#define SET_VERTICAL_DIFF 0x50
#define SET_HORIZONTAL_DIFF 0x51
#define SET_VERTICAL 0x52
#define SET_HORIZONTAL 0x53
#define GET_POSITION 0x60

/*
 The struct that is passed around for serial communication
*/
typedef struct _SerialConn
{
   int fd; // handle to the connection
   unsigned char txBuffer[20]; // transmission buffer (not used in current implementation)
	unsigned char rxBuffer[1]; // receive buffer, only one byte is received at a time, so only one is needed
	unsigned char packetBuffer[20]; // packet buffer, incomplete packets are put here
	int length; // length of the packet so far
	int state; // state, one of START, FRAMEDLE, DATA, DATADLE
	char checksum; // calculated checksum of the message
} SerialConn ;

/* Parses the next byte */
int parse_next(SerialConn* conn, unsigned char next);

/* Writes a packet to the serial connection, also performs escaping and adds start and end bytes */
void write_packet(int fd, unsigned char* msg, int length);

#endif /* PROTOCOL_H_ */
